package service

import (
	"context"
	pb "medicine/api/medicine/v1"
	"medicine/internal/biz"
	"time"
)

// SeckillService 秒杀服务实现，处理秒杀商品和活动相关的 gRPC 请求
type SeckillService struct {
	pb.UnimplementedSeckillServer                            // gRPC 秒杀服务基类
	spuc                          *biz.SeckillProductUsecase // 秒杀商品用例层依赖
	euc                           *biz.SeckillEventUsecase   // 秒杀活动用例层依赖
}

// NewSeckillService 创建秒杀服务实例
func NewSeckillService(spuc *biz.SeckillProductUsecase, euc *biz.SeckillEventUsecase) *SeckillService {
	return &SeckillService{spuc: spuc, euc: euc}
}

// ListSeckillProduct 获取秒杀商品列表（带商品、活动、状态等信息）
func (s *SeckillService) ListSeckillProduct(ctx context.Context, req *pb.ListSeckillProductRequest) (*pb.ListSeckillProductReply, error) {
	page := int(req.Page)
	if page <= 0 {
		page = 1
	}
	pageSize := int(req.PageSize)
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 20
	}
	details, total, err := s.spuc.ListDetail(ctx, page, pageSize)
	if err != nil {
		return nil, err
	}
	var products []*pb.SeckillProductReply
	for _, d := range details {
		products = append(products, &pb.SeckillProductReply{
			Id:             d.ID,
			ProductId:      d.ProductID,
			SeckillPrice:   d.SeckillPrice,
			SeckillStock:   int32(d.SeckillStock),
			SeckillStart:   d.SeckillStart.Format("2006-01-02 15:04:05"),
			SeckillEnd:     d.SeckillEnd.Format("2006-01-02 15:04:05"),
			SeckillEventId: d.SeckillEventID,
			ProductName:    d.ProductName,
			ProductImage:   d.ProductImage,
			OriginPrice:    d.OriginPrice,
			EventName:      d.EventName,
			Status:         d.Status,
		})
	}
	return &pb.ListSeckillProductReply{
		Products: products,
		Total:    int32(total),
	}, nil
}

// GetSeckillProduct 获取秒杀商品详情（带商品、活动、状态等信息）
func (s *SeckillService) GetSeckillProduct(ctx context.Context, req *pb.GetSeckillProductRequest) (*pb.GetSeckillProductReply, error) {
	detail, err := s.spuc.GetDetail(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &pb.GetSeckillProductReply{
		Product: &pb.SeckillProductReply{
			Id:             detail.ID,
			ProductId:      detail.ProductID,
			SeckillPrice:   detail.SeckillPrice,
			SeckillStock:   int32(detail.SeckillStock),
			SeckillStart:   detail.SeckillStart.Format("2006-01-02 15:04:05"),
			SeckillEnd:     detail.SeckillEnd.Format("2006-01-02 15:04:05"),
			SeckillEventId: detail.SeckillEventID,
			ProductName:    detail.ProductName,
			ProductImage:   detail.ProductImage,
			OriginPrice:    detail.OriginPrice,
			EventName:      detail.EventName,
			Status:         detail.Status,
		},
	}, nil
}

// CreateSeckillEvent 发布秒杀活动
func (s *SeckillService) CreateSeckillEvent(ctx context.Context, req *pb.CreateSeckillEventRequest) (*pb.SeckillEventReply, error) {
	e := &biz.SeckillEvent{
		Name:      req.Name,
		StartTime: parseTime(req.StartTime),
		EndTime:   parseTime(req.EndTime),
		Status:    1,
	}
	newE, err := s.euc.Create(ctx, e)
	if err != nil {
		return nil, err
	}
	return &pb.SeckillEventReply{
		Id:        newE.ID,
		Name:      newE.Name,
		StartTime: newE.StartTime.Format("2006-01-02 15:04:05"),
		EndTime:   newE.EndTime.Format("2006-01-02 15:04:05"),
		Status:    int32(newE.Status),
	}, nil
}

// ListSeckillEvent 获取秒杀活动列表
func (s *SeckillService) ListSeckillEvent(ctx context.Context, req *pb.ListSeckillEventRequest) (*pb.ListSeckillEventReply, error) {
	events, total, err := s.euc.List(ctx, int(req.Page), int(req.PageSize))
	if err != nil {
		return nil, err
	}
	var replies []*pb.SeckillEventReply
	for _, e := range events {
		replies = append(replies, &pb.SeckillEventReply{
			Id:        e.ID,
			Name:      e.Name,
			StartTime: e.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:   e.EndTime.Format("2006-01-02 15:04:05"),
			Status:    int32(e.Status),
		})
	}
	return &pb.ListSeckillEventReply{Events: replies, Total: int32(total)}, nil
}

// CreateSeckillProduct 添加秒杀商品
func (s *SeckillService) CreateSeckillProduct(ctx context.Context, req *pb.CreateSeckillProductRequest) (*pb.SeckillProductReply, error) {
	sp, err := s.spuc.CreateWithStock(ctx, &biz.SeckillProduct{
		ProductID:      req.ProductId,
		SeckillPrice:   req.SeckillPrice,
		SeckillStock:   int(req.SeckillStock),
		SeckillStart:   parseTime(req.SeckillStart),
		SeckillEnd:     parseTime(req.SeckillEnd),
		SeckillEventID: req.SeckillEventId,
	}, int(req.SeckillStock))
	if err != nil {
		return nil, err
	}
	return &pb.SeckillProductReply{
		Id:             sp.ID,
		ProductId:      sp.ProductID,
		SeckillPrice:   sp.SeckillPrice,
		SeckillStock:   int32(sp.SeckillStock),
		SeckillStart:   sp.SeckillStart.Format("2006-01-02 15:04:05"),
		SeckillEnd:     sp.SeckillEnd.Format("2006-01-02 15:04:05"),
		SeckillEventId: sp.SeckillEventID,
	}, nil
}

// parseTime 字符串转时间
func parseTime(s string) (t time.Time) {
	t, _ = time.Parse("2006-01-02 15:04:05", s)
	return
}
